package cn.net.awit.weaapp.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.net.awit.API.entity.JSONResult;
import cn.net.awit.weaapp.entity.WeaAppEntity;
import cn.net.awit.weaapp.service.WeaAppServiceI;
import net.sf.json.JSONArray;

/**   
 * @Title: Controller  
 * @Description: 移动端更新
 * @author onlineGenerator
 * @date 2018-11-21 16:18:11
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/weaAppController")
public class WeaAppController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(WeaAppController.class);

	@Autowired
	private WeaAppServiceI weaAppService;
	@Autowired
	private SystemService systemService;
	


	/**
	 * 移动端更新列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("cn/net/awit/weaapp/weaAppList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(WeaAppEntity weaApp,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(WeaAppEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, weaApp, request.getParameterMap());
		try{
		//自定义追加查询条件
		
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.weaAppService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除移动端更新
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(WeaAppEntity weaApp, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		weaApp = systemService.getEntity(WeaAppEntity.class, weaApp.getId());
		message = "移动端更新删除成功";
		try{
			weaAppService.delete(weaApp);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "移动端更新删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除移动端更新
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "移动端更新删除成功";
		try{
			for(String id:ids.split(",")){
				WeaAppEntity weaApp = systemService.getEntity(WeaAppEntity.class, 
				id
				);
				weaAppService.delete(weaApp);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "移动端更新删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加移动端更新
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(WeaAppEntity weaApp, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "移动端更新添加成功";
		try{
			Date date = new Date();
			weaApp.setAddTime(date);
			List<Map<String,Object>> list = 
					weaAppService.findForJdbc("select top 1 * from wea_app where file_panel = ? order by version_num desc", weaApp.getFilePanel());
			if (list.size()>0) {
				Map<String, Object> map = list.get(0);
				Integer versionnum = (Integer) map.get("version_num");
				versionnum++;
				weaApp.setVersionNum(versionnum);
			}else {
				weaApp.setVersionNum(1);
			}
			weaAppService.save(weaApp);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "移动端更新添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新移动端更新
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(WeaAppEntity weaApp, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "移动端更新更新成功";
		WeaAppEntity t = weaAppService.get(WeaAppEntity.class, weaApp.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(weaApp, t);
			weaAppService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "移动端更新更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param weaAppId
	 * @param file
	 * @return
	 */
	@RequestMapping(params = "doUpload",method=RequestMethod.POST)
	@ResponseBody
	public JSONResult doUpload( HttpServletRequest request,String weaAppId,@RequestParam("appFile")MultipartFile file) {
		JSONResult jsonResult = new JSONResult(1, "移动端更新文件上传成功");
		try {
			//weaApp的实体对象
			WeaAppEntity t = weaAppService.get(WeaAppEntity.class, weaAppId);
			//webUploader的文件key
			String fileKey = request.getParameter("id");
			//文件大小
			String sizeStr = request.getParameter("size");
			//表示存在文件
			if(StringUtil.isNotEmpty(fileKey)){
				//获取上传文件的保存目录
				String savePath = request.getServletContext().getRealPath("/upload/appfile");
				//上传文件名,带后缀
				String fileName = file.getOriginalFilename();
				//获取文件拓展名
				String extension = fileName.substring(fileName.lastIndexOf("."));
				//真正的文件名称，由时间戳+后缀名组成
				String realName = String.valueOf(System.currentTimeMillis())+extension;
				File realPath = new File(savePath, realName);
				if(!realPath.exists()){
					realPath.mkdirs();
				}
				file.transferTo(realPath);
				int i = Integer.parseInt(sizeStr);
				//设置文件大小和文件名称
				t.setFileSize(i/(1024*1024));
				t.setFileName(realName);
				weaAppService.saveOrUpdate(t);
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult.setCode(0);
			jsonResult.setMsg("移动端更新文件上传失败");
			throw new BusinessException(e.getMessage());
		}
		return jsonResult;
	}

	/**
	 * 移动端更新新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(WeaAppEntity weaApp, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(weaApp.getId())) {
			weaApp = weaAppService.getEntity(WeaAppEntity.class, weaApp.getId());
			req.setAttribute("weaApp", weaApp);
		}
		return new ModelAndView("cn/net/awit/weaapp/weaApp-add");
	}
	/**
	 * 移动端更新编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(WeaAppEntity weaApp, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(weaApp.getId())) {
			weaApp = weaAppService.getEntity(WeaAppEntity.class, weaApp.getId());
			req.setAttribute("weaApp", weaApp);
		}
		return new ModelAndView("cn/net/awit/weaapp/weaApp-update");
	}
	/**
	 * 移动端更新编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpload")
	public ModelAndView goUpload(WeaAppEntity weaApp, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(weaApp.getId())) {
			weaApp = weaAppService.getEntity(WeaAppEntity.class, weaApp.getId());
			req.setAttribute("weaApp", weaApp);
		}
		return new ModelAndView("cn/net/awit/weaapp/weaApp-upload");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","weaAppController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(WeaAppEntity weaApp,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(WeaAppEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, weaApp, request.getParameterMap());
		List<WeaAppEntity> weaApps = this.weaAppService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"移动端更新");
		modelMap.put(NormalExcelConstants.CLASS,WeaAppEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("移动端更新列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,weaApps);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(WeaAppEntity weaApp,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"移动端更新");
    	modelMap.put(NormalExcelConstants.CLASS,WeaAppEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("移动端更新列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<WeaAppEntity> listWeaAppEntitys = ExcelImportUtil.importExcel(file.getInputStream(),WeaAppEntity.class,params);
				for (WeaAppEntity weaApp : listWeaAppEntitys) {
					weaAppService.save(weaApp);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	
}
